﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;
using CloudTrace.Reader;
using CloudTrace;

namespace Viewer.Windows
{
    public partial class AppForm : Form
    {
        private delegate void ShowMessagesDelegate(string[] messages, int messageCount);
        ShowMessagesDelegate showMessage;
        private bool abort;
        private int maxMessages;
        private bool plainTextFormat = true;

        public AppForm()
        {
            InitializeComponent();
            this.maxMessages = (int)readBuffer.Value;

            plainTextFormat = bool.Parse(ConfigurationManager.AppSettings["usePlainText"] ?? bool.TrueString);

            this.showMessage = ShowMessages;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            radioButton1.Checked = true;
            base.OnClosing(e);
        }

        internal void ShowMessages(string[] messages, int messageCount)
        {
            int i;
            int maxLines = (int)rowBuffer.Value;
            StringBuilder builder = new StringBuilder(messages[0]);

            for (i = 1; i < messages.Length; i++)
            {
                if (messages[i].EndsWith(Environment.NewLine))
                    builder.Append(messages[i]);
                else
                    builder.AppendLine(messages[i]);

                if (i > maxLines)
                    break;
            }

            foreach (string message in textBox1.Lines)
            {
                if (message.EndsWith(Environment.NewLine))
                    builder.Append(message);
                else
                    builder.AppendLine(message);
                if (i++ > maxLines)
                    break;
            }

            this.textBox1.Text = builder.ToString();

            this.lblMessageCount.Text = "Remaining messages: " + messageCount.ToString();
        }

        private void BackgroundWorker()
        {
            QueueReader reader = new QueueReader();
            string[] messages;
            while (!abort)
            {
                reader.MaxBatchSize = this.maxMessages;
                if (plainTextFormat)
                {
                    messages = reader.GetPlainTextMessages();
                    while (messages != null && messages.Length > 0)
                    {
                        this.Invoke(showMessage, new object[] { messages, reader.MessageCount });

                        if (abort)
                            break;
                        reader.MaxBatchSize = this.maxMessages;
                        messages = reader.GetPlainTextMessages();
                    }
                }
                else
                {
                    LogMessage[] logMessages = reader.GetLogMessages();
                    while (logMessages != null && logMessages.Length > 0)
                    {
                        messages = new string[logMessages.Length];
                        for (int i = 0; i < logMessages.Length; i++)
                        {
                            LogMessage logMessage = logMessages[i];
                            messages[i] = logMessage.Timestamp.ToString() + (string.IsNullOrEmpty(logMessage.TraceEventType) ? string.Empty : " " + logMessage.TraceEventType)
                                + " " + (logMessage.Category ?? string.Empty) + ": " + logMessage.Message;
                        }
                        this.Invoke(showMessage, new object[] { messages, reader.MessageCount });

                        if (abort)
                            break;
                        reader.MaxBatchSize = this.maxMessages;
                        logMessages = reader.GetLogMessages();

                    }
                }
                Thread.Sleep(1000);
            }
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            abort = radioButton1.Checked;
            if (!abort)
            {
                new Thread(new ThreadStart(BackgroundWorker)).Start();
            }
        }

        private void textBox1_DoubleClick(object sender, EventArgs e)
        {
            textBox1.Text = string.Empty;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void readBuffer_ValueChanged(object sender, EventArgs e)
        {
            this.maxMessages = (int)readBuffer.Value;
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }
    }
}
